package com.ovopark.firecar.okhttp

import com.socks.library.KLog
import okhttp3.Interceptor
import okhttp3.Response
import retrofit2.Invocation
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 超时拦截器.
 * @author caixingming 2020/10/21.
 */
class TimeOutInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        //获取headers
        val invocation = request.tag(Invocation::class.java)
        val method = invocation?.method()
        //获取 DynamicTimeOUt
        val timeout = method?.getAnnotation(DynamicTimeout::class.java)
        KLog.i(TAG, "invocation", invocation?.toString() ?: "")
        return if (null != timeout && timeout.timeout > 0) {
            chain.withConnectTimeout(timeout.timeout, TimeUnit.SECONDS)
                    .withReadTimeout(timeout.timeout, TimeUnit.SECONDS)
                    .withWriteTimeout(timeout.timeout, TimeUnit.SECONDS)
                    .proceed(request)
        } else chain.proceed(request)
    }

    companion object {
        private const val TAG = "TimeOutInterceptor"
    }
}